package qeug.shsh.task;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.exception.KDException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import qeug.shsh.helper.FacadeHelper;
import qeug.shsh.task.taskInfo.CustomInfo;
import qeug.shsh.task.taskInfo.UnitBankList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;

public class SupplierToMDMTaskPlugin extends AbstractTask {
    /**
     * 员工供应商
     */
    private static final Log log1 = LogFactory.getLog(SupplierToMDMTaskPlugin.class);

    String heart = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:a=\"http://a.test.pcitc.com/\">\n" +
            "   <soapenv:Header/>\n" +
            "   <soapenv:Body>\n" +
            "      <a:Main_Service>\n" +
            "         <Busid>59003e0b2aab41378f9bbbdf0ef46cbc</Busid>\n" +
            "         <Appid>PRD800</Appid>\n" +
            "         <Appname>调用系统</Appname>\n" +
            "         <Ip>10.14.13.40</Ip>\n" +
            "         <Userid>50101010</Userid>\n" +
            "         <Version>version1.0</Version>\n" +
            "         <Isencryption>1</Isencryption>\n" +
            "         <Encryptiontype>Base64</Encryptiontype>\n" +
            "         <Iscompression>0</Iscompression>\n" +
            "         <Compressiontype></Compressiontype>\n" +
            "         <Mainstring><![CDATA[<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
            " <Xml_Format xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">";

    String last = "</Xml_Format>]]> </Mainstring>\n" +
            "         <Mainformart>1</Mainformart>\n" +
            "         <Remark>测试系统备注</Remark>\n" +
            "         <Serviceappid>TEST01</Serviceappid>\n" +
            "         <Serviceappname>测试系统</Serviceappname>\n" +
            "         <Serviceusername></Serviceusername>\n" +
            "         <Servicepassword></Servicepassword>\n" +
            "         <Servicemodule>MDM_RRE_0010</Servicemodule>\n" +
            "         <Servicemodulename>供应商注册</Servicemodulename>\n" +
            "      </a:Main_Service>\n" +
            "   </soapenv:Body>\n" +
            "</soapenv:Envelope>";

    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {

        String mdm_url = System.getProperty("mdm.url");
        String basicAuthUserName = System.getProperty("mdm.user");//名字
        String basicAuthPassword = System.getProperty("mdm.password");//编码

        String Xml = "";
        SortedMap<String, Object> tree = new TreeMap<String, Object>();
        DynamicObject[] suppliers = BusinessDataServiceHelper.
                load("bd_supplier", "id", new QFilter[]{new QFilter("type", "=", "4")
                        .and(new QFilter("qeug_istomdm", "=", true))});//伙伴类型为个人且是否传MDM复选框为是
        for (DynamicObject dynamicObject1 : suppliers) {
            DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(dynamicObject1.get("id"), "bd_supplier");

            //日志
            HashMap<String, Object> log = new HashMap<>();
            log.put("operationModule", "人员供应商同步MDM");
            log.put("url", mdm_url);
            log.put("user", basicAuthUserName);
            log.put("mode", "POST");
            log.put("action", "");
            log.put("opdate", new Date());
            Date modifytime = dynamicObject.getDate("modifytime");//修改时间
            Date qeug_importtime = dynamicObject.getDate("qeug_importtime");//同步时间

            if (qeug_importtime != null && modifytime.before(qeug_importtime)) {
                //修改时间是否在同步时间之前
                continue;
            }
//    public void beforeItemClick(BeforeItemClickEvent evt) {//
//        String operationKey = evt.getOperationKey();
//        if ("donothing".equals(operationKey)) {
//            String Xml = "";
//            Object[] primaryKeyValues = this.getSelectedRows().getPrimaryKeyValues();
//            for (Object primaryKeyValue : primaryKeyValues) {
//                long longValue = (long) primaryKeyValue;
//                DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle("bd_supplier", new QFilter("id", "=", longValue).toArray());//

            CustomInfo customInfo = new CustomInfo();
            List<UnitBankList> unitBankLists = new ArrayList<>();
            String number = dynamicObject.getString("number");//编码
            String name = dynamicObject.getString("name");//名称
            String idno = dynamicObject.getString("idno");//身份证号
            String phone = dynamicObject.getString("bizpartner_phone");//电话
            String email = dynamicObject.getString("postal_code");//电子邮箱
            DynamicObject employee = dynamicObject.getDynamicObject("employee");//员工
            DynamicObject person = BusinessDataServiceHelper.loadSingle(employee.get("id"), "bos_user");
            Object gender = person.get("gender");//性别
            Object orgID = person.getDynamicObjectCollection("entryentity").
                    get(0).getDynamicObject("dpt").get("id");
            DynamicObject org = BusinessDataServiceHelper.loadSingle(orgID, "bos_org");
            String depName = org.getString("name");//部门长名称

            //银行信息分录
            DynamicObjectCollection entry_bank = dynamicObject.getDynamicObjectCollection("entry_bank");
            for (int i = 0; i < entry_bank.size(); i++) {
                UnitBankList unitBankList = new UnitBankList();
                DynamicObject bank = entry_bank.get(i);
                bank.getDynamicObject("bank").getString("number");
                unitBankList.setBANK_ACCOUNT(bank.getString("bankaccount"));//银行国家
//                unitBankList.setBANK_CODE("103307043728");//银联号bank.getDynamicObject("bank").getString("number")
                unitBankList.setBANK_CODE(bank.getDynamicObject("bank").getString("number"));
//                unitBankList.setBANK_NAME("中国农业银行股份有限公司连云港港口支行");//开户行bank.getDynamicObject("bank").getString("name")
                unitBankList.setBANK_NAME(bank.getDynamicObject("bank").getString("name"));//开户行bank.getDynamicObject("bank").getString("name")

//                unitBankList.put("BANK_ACCOUNT", bank.getString("bankaccount"));//银行账号
//                unitBankList.setBANK_ACCOUNT_NAME("中国农业银行股份有限公司连云港港口支行");//开户名称bank.getString("accountname")
                unitBankList.setBANK_ACCOUNT_NAME(bank.getString("accountname"));//开户名称bank.getString("accountname")
                unitBankList.setBANK_CURRENCY("人民币");//币种
//                String bankList = FacadeHelper.mapToXml(tree, "", "unitBankList");
//                Xml = Xml + bankList;
                unitBankLists.add(unitBankList);
                customInfo.setUnitBankLists(unitBankLists);
            }
            Xml = "<UNITBANKLISTS>" + Xml + "</unitBankList></UNITBANKLISTS>";
/*                if (qeug_importtime != null) { //新增的供应商不传编码
                    customInfo.setOU_CODE(number);//MDM供应商编码
                } else {
                    customInfo.setOU_CODE("");
                }*/
            customInfo.setCHECKTYPE("1");//1：新增，2:编辑，3启用 4冻结
            customInfo.setOU_FULLNAME(name + number);//单位全称
            customInfo.setOU_SHORTNAME(name + number);//单位简称
            customInfo.setOU_PROVIDERGROUP("SK98");//供应商账户组
            customInfo.setOU_GSDJH("");//工商登记证号
            customInfo.setOU_ZZJGM("");//组织机构证号
            customInfo.setOU_SWDJH("");//税务登记证号
            customInfo.setOU_TYSHXYDM("");//统一信用代码证
            customInfo.setOU_GRYXZJH(idno);//个人有限证件号
            customInfo.setOU_COUNTRY("中国");//国家
            customInfo.setOU_AREA("江苏");//地区
            customInfo.setOU_CITY("连云港市");//城市
            customInfo.setOU_ADDRESS(depName);//地址
            customInfo.setOU_POSTCODE("222000");//邮编
            customInfo.setOU_TEL(phone);//电话
            customInfo.setOU_FAX(number);//传真
            customInfo.setOU_EMAIL(email);//电子邮箱
            customInfo.setOU_DWXZ(gender.toString());//单位性质
//            tree.put("OU_MYHB", "");//贸易伙伴
            customInfo.setOU_ISMATERIAL("否");//是否原料供应商

            try {
                Xml = getXmlWithoutHeader(customInfo);
            } catch (JAXBException | UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
            Xml = heart + Xml + last;
            log1.info("供应商注册接收到的发送报文：" + Xml);
            log.put("mainstring", Xml);

            String supJson = HttpRequest.post(mdm_url)
                    .body(Xml)
                    .execute().body();
            log1.info("供应商注册接收到的反回报文：" + supJson);
            String toJson = FacadeHelper.xmlJson(supJson);
//            Element element = FacadeHelper.praseXml(supJson);
//            Element backinfoElement = (Element) element.getElementsByTagName("BACKINFO").item(0);
            JSONObject jsonObject = JSONObject.parseObject(toJson);
            log1.info("供应商注册解析后的返回报文：" + toJson);
            log.put("responsebody", toJson);
            JSONObject jsInfo = jsonObject.getJSONObject("Body");
            JSONObject response = jsInfo.getJSONObject("Main_ServiceResponse");
            if (response != null) {
                String xml = jsInfo.getJSONObject("Main_ServiceResponse").getString("response1");
                String xmlJson = FacadeHelper.xmlJson(xml);
                JSONObject backinfo = JSONObject.parseObject(xmlJson).getJSONObject("BACKINFO");
                String status = backinfo.getString("STATUS");
                String msg = backinfo.getString("MSG");
                String code = backinfo.getString("CODE");
                if ("S".equals(status)) { //成功
                    //反写供应商数据，
                    log.put("pdesc", "成功");
                    FacadeHelper.apiLog(log);
                    dynamicObject.set("number", code);
                    dynamicObject.set("qeug_importtime", new Date());
                    OperationResult operationResult = SaveServiceHelper.saveOperate("save", "bd_supplier", new DynamicObject[]{dynamicObject}, OperateOption.create());
                } else { //失败
                    log1.info("供应商" + name + number + "同步失败", "原因：" + msg);
                    log.put("pdesc", "失败");
                    FacadeHelper.apiLog(log);
                    dynamicObject.set("qeug_reson", msg);
                    OperationResult operationResult = SaveServiceHelper.saveOperate("save", "bd_supplier", new DynamicObject[]{dynamicObject}, OperateOption.create());
                }
            } else {
                log.put("pdesc", "失败");
                FacadeHelper.apiLog(log);
                JSONObject basckObject = jsInfo.getJSONObject("Fault");
                String faultcode = basckObject.getString("faultcode");
                String faultstring = basckObject.getString("faultstring");
                log1.info("供应商" + name + number + "同步失败", "原因：" + faultstring);
                dynamicObject.set("qeug_reson", faultstring);
                OperationResult operationResult = SaveServiceHelper.saveOperate("save", "bd_supplier", new DynamicObject[]{dynamicObject}, OperateOption.create());
            }


            System.out.println(supJson);
        }
    }


    public synchronized static String getXmlWithoutHeader(CustomInfo customInfo) throws JAXBException, UnsupportedEncodingException {
        //1、创建JAXB对象，用于映射java类和XML
        JAXBContext context = JAXBContext.newInstance(customInfo.getClass());

        //2、创建Marshaller对象，用于将java对象序列号为XML
        Marshaller marshaller = context.createMarshaller();

        //3、配置Marshaller参数，例如XML的输出格式、是否格式化输出等
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");//编码格式
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);//是否格式化生成xml串
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);//是否省略xml头信息

        //4、调用Marshaller的marshal方法将java对象序列化为XML，并存储到ByteArrayOutPutStream(可以将数据写入到内存中的输出流)
        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
        marshaller.marshal(customInfo, dataStream);
        return dataStream.toString("UTF-8");
    }
}
